// import myrequest from "@/utils/request.js"

function check(param = {}) {
	// const myrequest=this.$myrequest
	// 合并默认参数
	param = Object.assign({
		title: "检测到有新版本！",
		content: "请升级app到最新版本！",
		canceltext: "暂不升级",
		oktext: "立即升级"
	}, param)
	plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
		let platform = plus.os.name.toLocaleLowerCase()
		console.log('开始检测更新')
		uni.request({
			// url:"http://192.168.1.16:8081/sysAppVersion/getAppVersionMsg",   //开发环境
			url:"https://3510b38g11.zicp.fun:443/sysAppVersion/getAppVersionMsg", //生产环境
			method: "POST",
			// success()
		}).then(res=> {
			console.log(res[1])
			let data = res[1].data.data ? res[1].data.data : null;
			console.log(data)
			console.log(widgetInfo.versionCode)//101
			console.log(widgetInfo.version)//1.0.1
			if (widgetInfo.versionCode === data.versionCode) {
				uni.setStorageSync('appVersion',widgetInfo.version)
				return;
			}
			// android进行如下操作
			console.log("检测app更新")
			console.log(data)
			uni.showModal({
				title: param.title,
				content: data.log ? data.log : param.content,
				showCancel: data.force ? false : true,
				confirmText: param.oktext,
				cancelText: param.canceltext,
				success: res => {
					if (!res.confirm) {
						console.log('取消了升级');
						plus.runtime.quit();
					}
					// if (data.shichang === 1) {
					// 	//去应用市场更新
					// 	plus.runtime.openURL(data.shichangurl);
					// 	plus.runtime.restart();
					// }
					 else {
						// 清除缓存
						// $request.clearLogin();

						// 开始下载
						// 创建下载任务
						var dtask = plus.downloader.createDownload(data
							.versionUrl, {
								filename: "_downloads/"
							},
							function(d, status) {
								// 下载完成
								if (status == 200) {
									plus.runtime.install(d.filename, {
										force: true
									}, function() {
										//进行重新启动;
										plus.runtime.restart();
									}, (e) => {
										uni.showToast({
											title: '安装升级包失败:' + JSON
												.stringify(e),
											icon: 'none'
										})
									});
								} else {
									this.tui.toast("下载升级包失败，请手动去站点下载安装，错误码: " +
										status);
								}
							});

						let view = new plus.nativeObj.View("maskView", {
							backgroundColor: "rgba(0,0,0,.6)",
							left: ((plus.screen.resolutionWidth / 2) - 45) +
								"px",
				 		bottom: "80px",
							width: "90px",
							height: "30px"
						})

						view.drawText('开始下载', {}, {
							size: '12px',
							color: '#FFFFFF'
						});
						view.show()
						dtask.addEventListener("statechanged", (e) => {
							if (e && e.downloadedSize > 0) {
								let jindu = ((e.downloadedSize / e.totalSize) *
									100).toFixed(2)
								view.reset();
								view.drawText('进度:' + jindu + '%', {}, {
									size: '12px',
									color: '#FFFFFF'
								});
				  	}
						}, false);
						dtask.start();
					}
				}
			})
		}).catch(e =>{
			console.log('出错！')
			console.log(e)
		})
	});
}

export default {
	check
}
